package gcb.metalsys.controller.auth;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import gcb.metalsys.entity.cop.CopDepartment;
import gcb.metalsys.service.cop.CopDepartmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import gcb.metalsys.base.ResultUtil;
import gcb.metalsys.base.dto.ResultDTO;
import gcb.metalsys.dto.auth.UserDTO;
import gcb.metalsys.enums.AccountEnum;
import gcb.metalsys.service.auth.AuthTableService;
import gcb.metalsys.service.auth.AuthUserService;
import gcb.metalsys.entity.auth.AuthUser;

import javax.validation.Valid;
import javax.ws.rs.POST;
import java.util.List;

@RestController
@RequestMapping("/authUser")
public class AuthUserController {

    @Autowired
    private AuthUserService authUserService;
    @Autowired
    private AuthTableService tableService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private CopDepartmentService copDepartmentService;

    @GetMapping("/info")
    @ApiOperation(value = "查询登录后用户信息")
    public ResultDTO getUserDetail(Authentication authentication) throws Exception {
        if (authentication == null) {
            throw new RuntimeException("未登录!");
        }
        return ResultUtil.Success(authUserService.getUserDetails(authentication));
    }

    @PostMapping("/admin/{roleId}")
    @ApiOperation(value = "用户注册(2.高级负责人 3.销售人员)")
    public ResultDTO insertAdmin(@RequestBody @Valid AuthUser authUser
                                 ,@PathVariable Long roleId,Authentication authentication,
                                 BindingResult bindingResult) throws Exception {
        if (roleId == 1) {
            throw new RuntimeException("非法角色");
        }
        if (bindingResult.hasErrors()) {
            return ResultUtil.Error(AccountEnum.Error.getCode().toString(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        /*
            设置所属
         */
        AuthUser controlUser = authUserService.getUserDetails(authentication);
        if (controlUser == null) {
            throw new RuntimeException("未登录");
        }
        if (controlUser.getUserGroup().equals(0L)) {
            authUser.setUserGroup(1L);
        }else {
            authUser.setUserGroup(controlUser.getUserId());
        }
        /*
            设置部门
         */
        if (controlUser.getUserDepartment().equals(0L)) {
            throw new RuntimeException("非法部门设置");
        }else {
            authUser.setUserDepartment(controlUser.getUserDepartment());
        }

        authUserService.signIn(authUser, roleId);
        return ResultUtil.Success(authUser);
    }

    @PutMapping
    @ApiOperation(value = "修改用户信息, 包含改密码")
    public ResultDTO updateById(@RequestBody AuthUser authUser) throws Exception {
        if (authUser.getUserPassword() != null) {
            AuthUser user = authUserService.getById(authUser.getUserId());
            if (user == null) {
                throw new RuntimeException("用户不存在!");
            }
            authUser.setUserPassword(passwordEncoder.encode(authUser.getUserPassword()));
        }

        authUserService.updateById(authUser);
        return ResultUtil.Success();
    }

    @DeleteMapping("/{id:\\d+}")
    @ApiOperation("根据Id删除用户")
    public ResultDTO deleteById(@PathVariable Long id) throws Exception {
        authUserService.removeById(id);
        return ResultUtil.Success();
    }

    @GetMapping
    @ApiOperation("查询全部用户,分页")
    public ResultDTO getUserList(@RequestParam(value = "page", defaultValue = "0") int pageNum,
                                 @RequestParam(value = "limit", defaultValue = "8") int pageSize) throws Exception {
        List<UserDTO> users = authUserService.selectUserInfo((pageNum-1), pageSize);
        for (UserDTO user : users) {
            for (UserDTO authUser : users) {
                if (user.getUserGroup().equals(authUser.getId())) {
                    user.setUserGroupName(authUser.getUserTrueName());
                }
            }
        }
        int count = authUserService.count();
        return ResultUtil.Success(users,count);
    }

    @GetMapping("/sameDepartment")
    @ApiOperation("查询同部门用户")
    public ResultDTO getSameDepartmentUser(Authentication authentication) throws Exception {
        AuthUser userDetails = authUserService.getUserDetails(authentication);
        QueryWrapper<AuthUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_department",userDetails.getUserDepartment());
        List<AuthUser> userList = authUserService.list(queryWrapper);
        int count = authUserService.count();
        return ResultUtil.Success(userList,count);
    }

    @GetMapping("/list")
    @ApiOperation("查询全部用户")
    public ResultDTO getAllUser() throws Exception {
        return ResultUtil.Success( authUserService.list());
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询用户")
    public ResultDTO getUserDetail(@PathVariable Long id) throws Exception {
        return ResultUtil.Success(authUserService.selectUserDetail(id));
    }

    @GetMapping("/parentGroup/{id:\\d+}")
    @ApiOperation("根据部门ID查询用户可选上司")
    public ResultDTO getParentGroup(@PathVariable Long id) throws Exception {
        QueryWrapper<AuthUser> authUserQueryWrapper = new QueryWrapper<>();
        authUserQueryWrapper.eq("user_department",id);
        List<AuthUser> parentGroup = authUserService.list(authUserQueryWrapper);
        return ResultUtil.Success(parentGroup);
    }

    /*
        {"children": [{"id": 2}],"id": 4}
    }
     */
    @ApiOperation(value = "更改用户角色关系")
    @PutMapping("/userRoleTable")
    public ResultDTO updateUserRole(@RequestBody UserDTO userDto) throws Exception {
        String type = StringUtils.substringBefore(userDto.getClass().getSimpleName().toLowerCase(), "dto");
        tableService.updateTable(userDto, type);
        return ResultUtil.Success();
    }

}
